<template>
  <div class="w-full h-full overflow-y-auto">
    <PageHeader :title="t('apply.business_info.经营信息')" />
    <div class="pl20 pr20 mt32">
      <LangTabs v-model="lang" />
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="300px"
      >
        <el-form-item :label="t('apply.business_info.店铺名称')" :prop="'name' + lang">
          <el-input
            v-model="formData['name' + lang]"
            :placeholder="t('apply.business_info.请输入店铺名称最多10个字')"
            style="width: 320px"
            maxlength="10"
          />
        </el-form-item>

        <el-form-item :label="t('apply.business_info.开店时长')" prop="ruleId">
          <el-select
            v-model="formData.ruleId"
            :placeholder="t('apply.business_info.请选择开店时长')"
            style="width: 320px"
          >
            <el-option
              v-for="item in ruleList"
              :key="item.id"
              :label="`${item.duration}${t('apply.business_info.年')} ${item.fee}${t('apply.business_info.元')}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('apply.business_info.经营类型')" prop="skuClassifyIds">
          <el-tree
            ref="treeRef"
            :data="businessTypeOptions"
            show-checkbox
            node-key="id"
            :props="{ label: 'name' + locale }"
            @check="handleCheckChange"
            :key="treeKey"
          />
        </el-form-item>
        <div class="titleRow">{{ t('apply.business_info.佣金比例及收款信息') }}</div>
        <el-form-item :label="t('apply.business_info.佣金比例')">
          <div class="fs-16 font-600">{{ configData.commissionRate ?? '--' }}%</div>
        </el-form-item>


        <el-form-item :label="t('apply.business_info.收款人姓名')">
          <div>{{ configData.accountBankAccountName ?? '--' }}</div>
        </el-form-item>
        <el-form-item :label="t('apply.business_info.收款账户号码')">
          <div>{{ configData.accountBankAccountNo ?? '--' }}</div>
        </el-form-item>
        <el-form-item :label="t('apply.business_info.收款银行名称')">
          <div>{{ configData.accountBankName ?? '--' }}</div>
        </el-form-item>
        <el-form-item :label="t('apply.business_info.收款银行地址')">
          <div>{{ configData.accountBankAddress ?? '--' }}</div>
        </el-form-item>
        <el-form-item :label="t('apply.business_info.SWIFT CODE')">
          <div>{{ configData.accountBankCode ?? '--' }}</div>
        </el-form-item>
        <el-form-item :label="t('apply.business_info.支付凭证')" prop="payImage">
          <UploadFile
            v-model="formData.payImage"
            :limit="1"
            :tip="t('apply.business_info.请上传支付凭证')"
            single-mode
            :file-size="2"
          />
        </el-form-item>

        <div class="flex_aic_jcc mt32">
          <el-button size="large" @click="prevStep">{{ t('apply.business_info.上一步') }}</el-button>
          <el-button type="primary" size="large" @click="submitForm"
            >{{ t('apply.business_info.提交审核') }}</el-button
          >
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import UploadFile from "@/components/UploadFile.vue";
import LangTabs from "@/components/LangTabs.vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { formData } from "../data";
import Api from "@/config/api/api";
import { useI18n } from "vue-i18n";
import i18n from "@/i18n";

const { locale, t } = useI18n();
const lang = ref(locale.value);
const langs = reactive(Object.keys(i18n.global.messages.value));
const router = useRouter();
const formRef = ref(null);
const treeRef = ref(null);
const treeKey = ref(0);
// 模拟经营类型数据
const businessTypeOptions = ref([]);
const ruleList = ref([]);
const configData = ref({});
// 如果表单中有已选择的类型，在树中显示为选中状态
onMounted(() => {
  getPlatformConfig()
  getRuleList();
  getBusinessCategory();
  if (
    formData.value.skuClassifyIds &&
    formData.value.skuClassifyIds.length > 0 &&
    treeRef.value
  ) {
    console.log(111111, formData.value.skuClassifyIds);
    treeRef.value.setCheckedKeys(formData.value.skuClassifyIds);
  }
});

watch(
  () => locale.value,
  () => {
    treeKey.value++;
  }
);

const getRuleList = async () => {
  const res = await Api.tenantRenewRule({ page: 0, size: 1000 });
  ruleList.value = res?.data?.content || [];
};

// 获取经营类目
const getBusinessCategory = async () => {
  const res = await Api.businessCategory();
  businessTypeOptions.value = res?.data || [];
};

// 验证上传图片的方法
const validateUpload = (rule, value, callback) => {
  if (!value || !value?.length) {
    callback(new Error(t('apply.business_info.请上传图片')));
  } else {
    callback();
  }
};

// 验证经营类型选择
const validateBusinessType = (rule, value, callback) => {
  if (!value || value.length === 0) {
    callback(new Error(t('apply.business_info.请选择经营类型')));
  } else {
    callback();
  }
};

// 监听树形结构选择变化
const handleCheckChange = () => {
  if (!treeRef.value) return;
  const checkedKeys = treeRef.value.getCheckedKeys();
  formData.value.skuClassifyIds = checkedKeys;
};

// 表单验证规则
const rules = reactive({
  ruleId: [{ required: true, message: t('apply.business_info.请选择开店时长'), trigger: "change" }],
  payImage: [{ required: true, message: t('apply.business_info.请上传支付凭证'), trigger: "change" }],
  skuClassifyIds: [
    { required: true, validator: validateBusinessType, trigger: "change" },
  ],
});

langs.forEach((item) => {
  formData.value["name" + item] = formData.value["name" + item] ?? "";
  rules["name" + item] = [
    { required: true, message: t('apply.business_info.请输入店铺名称'), trigger: "blur" },
    {
      min: 2,
      max: 30,
      message: t('apply.business_info.店铺名称长度应在2-30个字符之间'),
      trigger: "blur",
    },
  ];
});

// 上一步
const prevStep = () => {
  router.push("/apply/base_info");
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const params = {
        ...formData.value,
        payImage: formData.value.payImage[0]?.url,
        settleIdImage1: formData.value.settleIdImage1[0]?.url,
        settleIdImage2: formData.value.settleIdImage2[0]?.url,
        settleLicenseImage: formData.value.settleLicenseImage[0]?.url,
        settleExtra1: formData.value.settleExtra1[0]?.url,
        settleExtra2: formData.value.settleExtra2[0]?.url,
        settleExtra3: formData.value.settleExtra3[0]?.url,
      };
      const res = await Api.apply(params);
      if (res?.status == 200) {
        ElMessage.success(t('apply.business_info.提交成功您的入驻申请已提交'));
        setTimeout(() => {
          router.push("/apply/open_up");
        }, 1500);
      }
    } else {
      console.log("表单验证失败:", fields);
      ElMessage.error(t('apply.business_info.请完成必填信息'));
    }
  });
};

const getPlatformConfig = () => {
  Api.platformConfig().then(res=>{
    if(res?.status == 200){
      configData.value = res?.data || {}
    }
  })
};
</script>

<style scoped lang="scss">
:deep(.el-form-item) {
  margin-bottom: 30px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-tree) {
  max-height: 500px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  width: 500px;
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: 0 0 0 1px #f56c6c inset;
}
.titleRow {
  height: 36px;
  line-height: 36px;
  background: rgba(24, 144 ,255, 0.05);
  border-radius: 3px;
  padding-left: 10px;
  margin-bottom: 24px;
  font-weight: 500;
  color: #333;
}
</style>
